package com.autonomous_printer.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.autonomous_printer.mapper.OrderMapper;
import com.autonomous_printer.pojo.Order;
import com.autonomous_printer.service.PayService;
import com.autonomous_printer.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    OrderUtil orderUtil;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public String placeOrder(double money, int fileId) {
        Order order = new Order();
        order.setDatetime(new Date(System.currentTimeMillis()));
        order.setOrderNo(System.currentTimeMillis() + "");//订单编号
        order.setMoney(money);
        order.setFileId(fileId);

        try {
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + order.getOrderNo() + "\"," +//商户订单号
                    "    \"total_amount\":\"" + order.getMoney() + "\"," +
                    "    \"subject\":\"打印消费\"," +
                    "    \"store_id\":\"NJ_001\"," +
                    "    \"timeout_express\":\"6m\"}");//订单允许的最晚付款时间
            AlipayTradePrecreateResponse response = alipayClient.execute(request);

            //设置订单的属性
            order.setPayAddress(response.getQrCode());
            order.setTradeNo(response.getOutTradeNo());
            order.setStatus(0);
            //插入数据库
            orderMapper.addOrder(order);
            //放入全局的订单信息中
            orderUtil.put(order.getId(), order);
            //如果没有支付,定时取消订单
            cancelOrderTimer(order);

            return order.getId() + "";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 设置取消订单的定时器
     *
     * @param order
     */
    private void cancelOrderTimer(Order order) {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if ("failed".equals(queryPay(order.getId()))) {
                    cancelOrder(order.getId());
                }
            }
        };
        //五分钟后取消订单
        timer.schedule(task, 5 * 60 * 1000);
    }

    @Override
    public String queryPay(int id) {
        if (!orderUtil.contains(id)) {
            return null;
        }
        Order order = orderUtil.get(id);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + order.getOrderNo() + "\"," +
                "    \"trade_no\":\"\"}"); //设置业务参数
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
            if ("TRADE_SUCCESS".equals(response.getTradeStatus())) {
                //把该订单从全局信息中移除
                orderUtil.remove(id);
                //把数据库中订单状态改为1,表示已支付
                orderMapper.updateOrderStatus(id);
                return "success";
            }
            return "failed";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failed";
        }
    }

    @Override
    public boolean cancelOrder(int id) {
        if (!orderUtil.contains(id)) {
            return true;
        }
        Order order = orderUtil.get(id);
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();//创建API对应的request类
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + order.getOrderNo() + "\"," +
                "    \"trade_no\":\"\"}"); //设置业务参数
        try {
            AlipayTradeCancelResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
            String retryFlag = response.getRetryFlag();
            System.out.println(retryFlag);
            return true;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }
}
